# 把一个文件夹下所有文件（包括子文件夹的文件）全部集中到指定文件夹
# 实现方式有复制和移动两种，用户按需求选择，但是选择一种后，必须注释另一种
# 程序会自动生成【整理前后文件路径对照.txt】文件，内容为整理前和后的文件路径，保存在指定文件夹中
import os
import shutil
import time


def get_files_in_folder(folder_path):
    file_list = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_list.append(os.path.join(root, file))
    return file_list


def create_temp_list(file_list):
    timestamp = int(time.time())
    temp_list = []
    for f in file_list:
        suffix = f.split(sep='.')[-1]
        temp_path = dst_dir + os.sep + str(timestamp) + '.' + suffix
        temp_list.append(temp_path)
        timestamp = timestamp + 1
    return temp_list


def copy_files(file_list, temp_list):
    # 新旧文件的对照字典
    old_new_files_dict = {}
    for i in range(len(file_list)):
        src_file = file_list[i]
        dst_file = temp_list[i]
        try:
            # 复制文件
            shutil.copy2(src_file, dst_file)
            old_new_files_dict[src_file] = dst_file
            print(f"{src_file}已成功复制为{dst_file}")
        except FileNotFoundError:
            print(f"错误: 源文件 {src_file} 未找到。")
        except PermissionError:
            print("错误: 没有足够的权限进行操作。")
        except Exception as e:
            print(f"发生未知错误111: {e}")

    return old_new_files_dict


def move_files(file_list, temp_list):
    # 新旧文件的对照字典
    old_new_files_dict = {}
    for i in range(len(file_list)):
        source_path = file_list[i]
        destination_path = temp_list[i]
        try:
            # 检查源文件是否存在
            if os.path.exists(source_path):
                # 移动文件
                shutil.move(source_path, destination_path)
                old_new_files_dict[source_path] = destination_path
                print(f"文件已成功从 {source_path} 移动到 {destination_path}")
            else:
                print(f"错误：源文件 {source_path} 不存在。")
        except PermissionError:
            print("错误：没有足够的权限进行操作。")
        except Exception as e:
            print(f"发生未知错误222: {e}")
    return old_new_files_dict


def serialize_rename_files(folder_path, start_index, old_new_files_dict):
    try:
        # 获取文件夹下的所有文件
        file_list = []
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_list.append(os.path.join(root, file))
            break

        # 对文件进行序列化重命名
        for index, file_path in enumerate(file_list, start=start_index):
            file_ext = os.path.splitext(file_path)[1]
            new_file_name = f"{index}{file_ext}"
            new_file_path = os.path.join(folder_path, new_file_name)
            os.rename(file_path, new_file_path)
            if file_path in list(old_new_files_dict.values()):
                for k, v in old_new_files_dict.items():
                    if file_path == v:
                        old_new_files_dict[k] = new_file_path
            else:
                old_new_files_dict[file_path] = new_file_path
            print(f"已将 {file_path} 重命名为 {new_file_path}")
    except FileNotFoundError:
        print(f"错误: 文件夹 {folder_path} 未找到。")
    except PermissionError:
        print("错误: 没有足够的权限进行操作。")
    except Exception as e:
        print(f"发生未知错误333: {e}")

    return old_new_files_dict


def write_dict(old_new_files_dict, dst_dir):
    file_path = os.path.join(dst_dir, "整理前后文件路径对照.txt")
    with open(file_path, encoding='utf-8', mode='w') as f:
        for k, v in old_new_files_dict.items():
            f.write(f'{k}--->{v}')
            f.write(os.linesep)


if __name__ == '__main__':
    # 用户需要修改src_dir,dst_dir，并在步骤【3.执行临时重命名】中选择一种方式，必须注释另一种方式

    # 需要整理的文件夹
    src_dir = r'C:\Users\jimka\Downloads\123'
    # 用于保存的文件夹
    dst_dir = r'C:\Users\jimka\Downloads\123'

    # 1.获取原文件夹下所有文件到列表
    files_list = get_files_in_folder(src_dir)

    # 2.建立与文件列表大小相同，以时间戳为元素的等差列表
    temp_list = create_temp_list(files_list)

    # 3.执行临时重命名
    # 方法1：复制
    old_new_files_dict = copy_files(files_list, temp_list)
    # 方法2：移动
    # old_new_files_dict = move_files(files_list, temp_list)

    # 4.执行序列化重命名
    random_number = 2 * int(time.time())
    old_new_files_dict = serialize_rename_files(dst_dir, random_number, old_new_files_dict)
    old_new_files_dict = serialize_rename_files(dst_dir, 1, old_new_files_dict)

    # 5.记录修改结果并保存
    write_dict(old_new_files_dict, dst_dir)

    # 结束
    print('程序结束，请查看结果')
